package com.nail.api.customMake.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.nail.api.customMake.bean.Indent;
import com.nail.api.customMake.bean.Message;
import com.nail.api.customMake.service.IInDentService;
import com.nail.api.customMake.service.IMessageService;
import com.nail.api.user.bean.User;
import com.nail.client.RedisClient;
import com.nail.common.Constant;
import com.nail.controller.BaseController;
import com.nail.utils.IPUtils;
import com.nail.utils.PageResult;
import com.nail.utils.Result4API;
@Controller
@RequestMapping("/api/ident")
public class IndentController  extends BaseController{
	Logger logger = Logger.getLogger(this.getClass());

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Autowired
	private RedisClient redisClient;

	@Autowired
	private IInDentService inDentService;

	@Autowired
	private IMessageService messageService;

	static Map<Integer,Object> orderTypeMap = new HashMap<>();

	static{
		orderTypeMap.put(0,"nail stickers");
		orderTypeMap.put(1,"phone case");
		orderTypeMap.put(2,"nail plates");
	}

	@PostMapping(value="/addIndent")
	@ResponseBody
	public Result4API addIndent(HttpServletRequest request,Indent indent,String token){
		Result4API result = new Result4API();
		logger.info(sdf.format(new Date()) +" "+ IPUtils.getRemoteHost(request) + ",用户访问了本接口：addIndent" );

		if(indent == null || indent.getNum() == null || indent.getPrice() == null||
				indent.getIsTemplate() == null || indent.getOrderType() == null|| indent.getSource() == null ||
				indent.getIsAble() == null){
			result.setCode(Constant.API_CODE_501);
			result.setMsg(Constant.API_MSG_501);
			return result;
		}
		if(!StringUtils.isEmpty(indent.getImgIds())){
			String imgStr = indent.getImgIds().replaceAll("\\[","").replaceAll("\\]","").replaceAll("\"","");
			if(imgStr == null || StringUtils.isEmpty(imgStr.replaceAll(",","")) ){
				result.setCode(Constant.API_CODE_501);
				result.setMsg(Constant.API_MSG_501);
				return result;
			}
			indent.setImgIds(imgStr);
		}

		User user = (User)redisClient.get(Constant.REDIS_USER_KEY + token);
		indent.setOrderId(UUID.randomUUID().toString().replaceAll("-",""));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		indent.setOrderNum(sdf.format(new Date()));
		indent.setUserId(user.getId());
		indent.setUserName(user.getUserName());
		indent.setCreateTime(new Date());

		//订单默认状态
		indent.setIsDown(0);
		indent.setIsAffirm(0);
		indent.setPayStatus(0);
		indent.setState(0);


		try {
			inDentService.addIndent(indent);
			//管理员通知 --订单生成
			Message message = new Message();
			message.setAccepter(1L);
			message.setCreateTime(new Date());
			message.setIsRead(0);
			message.setOrderId(indent.getOrderId());
			//待翻译
			message.setMsg("来自" + user.getUserName() + "的订单, " + orderTypeMap.get(indent.getOrderType()) + " 定制!");
			message.setUserId(user.getId());
			message.setUserName(user.getUserName());
			messageService.addMessage(message);

			//客户通知 --订单生成
			Message messageCustom = new Message();
			messageCustom.setAccepter(user.getId());
			messageCustom.setCreateTime(new Date());
			messageCustom.setIsRead(0);
			messageCustom.setOrderId(indent.getOrderId());
			//待翻译
			messageCustom.setMsg("Your order:" + indent.getOrderNum() +", " + orderTypeMap.get(indent.getOrderType()) + " awaiting payment！");
			messageCustom.setUserId(user.getId());
			messageCustom.setUserName(user.getUserName());
			messageService.addMessage(messageCustom);

			result.setData(indent.getOrderId());
			result.setCode(Constant.API_CODE_SUCCESS);
			result.setMsg(Constant.API_MSG_SUCCESS);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.toString());
			result.setCode(Constant.API_CODE_ERROR);
			result.setMsg(Constant.API_MSG_ERROR);
			return result;
		}
	}

	/*@PostMapping(value="/deleteIndent")
    @ResponseBody
    public Result4API deleteIndent(HttpServletRequest request, String orderId, String token){
        Result4API result = new Result4API();
        logger.info(sdf.format(new Date()) +" "+ IPUtils.getRemoteHost(request) + ",用户访问了本接口：deleteIndent" );

        if(StringUtils.isEmpty(orderId) ){
            result.setCode(Constant.API_CODE_501);
            result.setMsg(Constant.API_MSG_501);
            return result;
        }
        try {
            User user = (User)redisClient.get(Constant.REDIS_USER_KEY + token);
        	inDentService.deleteIndent(user.getRole().getRoleType() == 0 ? user.getId():null,orderId);
            result.setCode(Constant.API_CODE_SUCCESS);
            result.setMsg(Constant.API_MSG_SUCCESS);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.toString());
            result.setCode(Constant.API_CODE_ERROR);
            result.setMsg(Constant.API_MSG_ERROR);
            return result;
        }
    }*/

	@PostMapping(value="/updateIndent")
	@ResponseBody
	public Result4API updateIndent(HttpServletRequest request,Indent indent,String token){
		Result4API result = new Result4API();
		logger.info(sdf.format(new Date()) +" "+ IPUtils.getRemoteHost(request) + ",用户访问了本接口：updateIndent" );

		if(indent ==null || StringUtils.isEmpty(indent.getOrderId())){
			result.setCode(Constant.API_CODE_501);
			result.setMsg(Constant.API_MSG_501);
			return result;
		}
		User user = (User)redisClient.get(Constant.REDIS_USER_KEY + token);
		indent.setModifier(user.getId());
		indent.setUpdateTime(new Date());
		if(indent.getWaybill() != null && indent.getExpress() != null){
			indent.setExpressTime(new Date());
			//客户通知 -- 发货
			Message messageCustom = new Message();
			messageCustom.setAccepter(indent.getUserId());
			messageCustom.setCreateTime(new Date());
			messageCustom.setIsRead(0);
			messageCustom.setOrderId(indent.getOrderId());
			//待翻译
			messageCustom.setMsg("Your order:" + indent.getOrderNum() +", " + orderTypeMap.get(indent.getOrderType())
			+ "  have been delivered！Express comapny:"+indent.getExpress()+" Express number: "+indent.getWaybill());
			messageCustom.setUserId(user.getId());
			messageCustom.setUserName(user.getUserName());
			messageService.addMessage(messageCustom);
		}
		if(indent.getState() != null && indent.getState() == 3){
			//客户确认收获  --通知管理员
			Message messageCustom = new Message();
			messageCustom.setAccepter(1L);
			messageCustom.setCreateTime(new Date());
			messageCustom.setIsRead(0);
			messageCustom.setOrderId(indent.getOrderId());
			//待翻译
			messageCustom.setMsg("客户： "+indent.getUserName() +" ,订单号: " + indent.getOrderNum() +" ,已经确认收货！");
			messageCustom.setUserId(user.getId());
			messageCustom.setUserName(user.getUserName());
			messageService.addMessage(messageCustom);
		}

		//付款通知
		//申请退款
		if(indent.getPayStatus() != null && indent.getPayStatus() == 2){
			//客户确认收获  --通知管理员
			Message messageCustom = new Message();
			messageCustom.setAccepter(1L);
			messageCustom.setCreateTime(new Date());
			messageCustom.setIsRead(0);
			messageCustom.setOrderId(indent.getOrderId());
			//待翻译
			messageCustom.setMsg("客户： "+indent.getUserName() +" ,订单号: " + indent.getOrderNum() +" ,申请退款,请与客户联系！");
			messageCustom.setUserId(user.getId());
			messageCustom.setUserName(user.getUserName());
			messageService.addMessage(messageCustom);
		}

		//退款成功
		if(indent.getPayStatus() != null && indent.getPayStatus() == 3){
			indent.setExpressTime(new Date());
			//客户通知 -- 发货
			Message messageCustom = new Message();
			messageCustom.setAccepter(indent.getUserId());
			messageCustom.setCreateTime(new Date());
			messageCustom.setIsRead(0);
			messageCustom.setOrderId(indent.getOrderId());
			//待翻译
			messageCustom.setMsg("Your order:" + indent.getOrderNum() +", " + orderTypeMap.get(indent.getOrderType())
			+ "is refund successful to PayPal");
			messageCustom.setUserId(user.getId());
			messageCustom.setUserName(user.getUserName());
			messageService.addMessage(messageCustom);
		}

		if(indent.getImgIds() != null){
			indent.setImgIds(indent.getImgIds().replaceAll("\\[","").replaceAll("\\]","").replaceAll("\"",""));
		}
		try {
			inDentService.updateIndent(indent);
			result.setCode(Constant.API_CODE_SUCCESS);
			result.setMsg(Constant.API_MSG_SUCCESS);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.toString());
			result.setCode(Constant.API_CODE_ERROR);
			result.setMsg(Constant.API_MSG_ERROR);
			return result;
		}
	}


	@PostMapping(value="/setSort")
	@ResponseBody
	public Result4API setSort(HttpServletRequest request,String orderId,Integer sort,String token){
		Result4API result = new Result4API();
		logger.info(sdf.format(new Date()) +" "+ IPUtils.getRemoteHost(request) + ",用户访问了本接口：setSort" );

		if(sort ==null || StringUtils.isEmpty(orderId)){
			result.setCode(Constant.API_CODE_501);
			result.setMsg(Constant.API_MSG_501);
			return result;
		}

		try {
			inDentService.setSort(orderId,sort);

			result.setCode(Constant.API_CODE_SUCCESS);
			result.setMsg(Constant.API_MSG_SUCCESS);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.toString());
			result.setCode(Constant.API_CODE_ERROR);
			result.setMsg(Constant.API_MSG_ERROR);
			return result;
		}
	}

	@PostMapping(value="/getIndent")
	@ResponseBody
	public Result4API getIndent(HttpServletRequest request,String token,Integer pageSize,Integer pageNo){
		Result4API result = new Result4API();
		logger.info(sdf.format(new Date()) +" "+ IPUtils.getRemoteHost(request) + ",用户访问了本接口：getIndent" );

		if(StringUtils.isEmpty(token)){
			result.setCode(Constant.API_CODE_501);
			result.setMsg(Constant.API_MSG_501);
			return result;
		}
		User user = (User)redisClient.get(Constant.REDIS_USER_KEY + token);
		PageResult pageResult = new PageResult();
		if(pageNo != null){
			pageResult.setPageNo(pageNo);
		}
		if(pageSize != null){
			pageResult.setPageSize(pageSize);
		}
		try {
			//管理员不过滤权限
			pageResult = inDentService.getIndentByUserId(user.getRole().getRoleType() == 0 ? user.getId():null,pageResult);
			result.setData(pageResult);
			result.setCode(Constant.API_CODE_SUCCESS);
			result.setMsg(Constant.API_MSG_SUCCESS);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.toString());
			result.setCode(Constant.API_CODE_ERROR);
			result.setMsg(Constant.API_MSG_ERROR);
			return result;
		}
	}



	@PostMapping(value="/getIndentByCondition")
	@ResponseBody
	public Result4API getIndentByCondition(HttpServletRequest request,String token,Integer pageSize,Integer pageNo,
			String condition ){
		Result4API result = new Result4API();
		logger.info(sdf.format(new Date()) +" "+ IPUtils.getRemoteHost(request) + ",用户访问了本接口：getIndentByCondition" );

		if(StringUtils.isEmpty(token) || StringUtils.isEmpty(condition)){
			result.setCode(Constant.API_CODE_501);
			result.setMsg(Constant.API_MSG_501);
			return result;
		}
		User user = (User)redisClient.get(Constant.REDIS_USER_KEY + token);
		PageResult pageResult = new PageResult();
		if(pageNo != null){
			pageResult.setPageNo(pageNo);
		}
		if(pageSize != null){
			pageResult.setPageSize(pageSize);
		}
		Map<String,Object> conditionMap = JSONObject.parseObject(condition);
		if(user.getRole().getRoleType() == 0){
			conditionMap.put("userId",user.getId());
		}
		try {
			//管理员不过滤权限
			pageResult = inDentService.getIndentByCondition(pageResult,conditionMap);
			result.setData(pageResult);
			result.setCode(Constant.API_CODE_SUCCESS);
			result.setMsg(Constant.API_MSG_SUCCESS);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.toString());
			result.setCode(Constant.API_CODE_ERROR);
			result.setMsg(Constant.API_MSG_ERROR);
			return result;
		}
	}


	@PostMapping(value="/getIndentById")
	@ResponseBody
	public Result4API getIndentById(HttpServletRequest request,String token,String orderId){
		Result4API result = new Result4API();
		logger.info(sdf.format(new Date()) +" "+ IPUtils.getRemoteHost(request) + ",用户访问了本接口：getIndentById" );

		if(StringUtils.isEmpty(token) || StringUtils.isEmpty(orderId)){
			result.setCode(Constant.API_CODE_501);
			result.setMsg(Constant.API_MSG_501);
			return result;
		}


		try {
			User user = (User)redisClient.get(Constant.REDIS_USER_KEY + token);
			Indent indent = null;
			if(user != null && user.getRole().getRoleType() == 1) {
				indent = inDentService.getIndentById(null, orderId);
			}else {
				indent = inDentService.getIndentById(user.getId(), orderId);
			}
			result.setData(indent);
			result.setCode(Constant.API_CODE_SUCCESS);
			result.setMsg(Constant.API_MSG_SUCCESS);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.toString());
			result.setCode(Constant.API_CODE_ERROR);
			result.setMsg(Constant.API_MSG_ERROR);
			return result;
		}
	}

	@PostMapping(value="/changeState")
	@ResponseBody
	public Result4API changeState(HttpServletRequest request,String token,String orderId,Integer state,String orderNum){
		Result4API result = new Result4API();
		logger.info(sdf.format(new Date()) +" "+ IPUtils.getRemoteHost(request) + ",用户访问了本接口：changeState" );

		if(StringUtils.isEmpty(token) || StringUtils.isEmpty(orderId) || state == null){
			result.setCode(Constant.API_CODE_501);
			result.setMsg(Constant.API_MSG_501);
			return result;
		}


		try {
			User user = (User)redisClient.get(Constant.REDIS_USER_KEY + token);
			if(user != null && user.getRole().getRoleType() == 1) {
				inDentService.changeState(null,orderId,state);
			}else {
				inDentService.changeState(user.getId(),orderId,state);
			}

			//客户确认收货
			if(!StringUtils.isEmpty(orderNum) && state == 3){
				//管理员通知
				Message message = new Message();
				message.setAccepter(1L);
				message.setCreateTime(new Date());
				message.setIsRead(0);
				message.setOrderId(orderId);
				//待翻译
				message.setMsg("来自" + user.getUserName() + "的订单,单号: " + orderNum + " 已经确认收货!");
				message.setUserId(user.getId());
				message.setUserName(user.getUserName());
				messageService.addMessage(message);
			}

			result.setCode(Constant.API_CODE_SUCCESS);
			result.setMsg(Constant.API_MSG_SUCCESS);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.toString());
			result.setCode(Constant.API_CODE_ERROR);
			result.setMsg(Constant.API_MSG_ERROR);
			return result;
		}
	}

}
